<template>
  <div class="user-management-container">
    <div class="header">
      <h2>用户管理</h2>
      <el-button type="primary" @click="handleAddUser">新增用户</el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 用户表格 -->
    <div class="table-container">
      <el-table :data="userList" border style="width: 100%" v-loading="loading">
        <el-table-column prop="user_id" label="ID" width="80" align="center" />
        <el-table-column prop="username" label="用户名" align="center" />
        <el-table-column prop="real_name" label="真实姓名" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-switch v-model="row.status" :active-value="1" :inactive-value="0" @change="handleStatusChange(row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right" align="center">
          <template #default="{ row }">
            <el-button @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" :close-on-click-modal="false">
      <el-form ref="userFormRef" :model="userForm" :rules="userRules" label-width="100px" label-position="right">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" :disabled="!isAdd" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="real_name">
          <el-input v-model="userForm.real_name" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="isAdd" label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item v-if="!isAdd" label="新密码" prop="new_password">
          <el-input v-model="userForm.new_password" type="password" placeholder="如需修改密码请填写" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getUserList,
  addUser,
  updateUser,
  deleteUser
} from '@/api/user'

// 数据
const loading = ref(false)
const userList = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isAdd = ref(true)
const userFormRef = ref()

// 表单数据
const userForm = reactive({
  user_id: '',
  username: '',
  real_name: '',
  status: 1,
  password: '',
  new_password: ''
})

// 搜索表单
const searchForm = reactive({
  username: ''
})

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表单验证规则
const userRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  real_name: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
})

// 生命周期钩子
onMounted(() => {
  fetchUserList()
})

// 获取用户列表
const fetchUserList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.current,
      size: pagination.size,
      ...searchForm
    }
    const res = await getUserList(params)
    userList.value = res.data.List || []
    pagination.total = res.data.total || 0
  } catch (error) {
    ElMessage.error('获取用户列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 搜索用户
const handleSearch = () => {
  pagination.current = 1
  fetchUserList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.username = ''
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  fetchUserList()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.current = current
  fetchUserList()
}

// 新增用户
const handleAddUser = () => {
  dialogTitle.value = '新增用户'
  isAdd.value = true
  resetForm()
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  dialogTitle.value = '编辑用户'
  isAdd.value = false
  Object.assign(userForm, {
    user_id: row.user_id,
    username: row.username,
    real_name: row.real_name,
    status: row.status,
    password: '',
    new_password: ''
  })
  dialogVisible.value = true
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该用户吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteUser(row.user_id)
      ElMessage.success('删除成功')
      fetchUserList()
    } catch (error) {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }).catch(() => { })
}

// 用户状态改变
const handleStatusChange = async (row) => {
  try {
    await updateUser({
      user_id: row.user_id,
      status: row.status,
      real_name: row.real_name
    })
    ElMessage.success('状态更新成功')
  } catch (error) {
    // 如果失败则回滚状态
    row.status = row.status === 1 ? 0 : 1
    ElMessage.error('状态更新失败')
    console.error(error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(userForm, {
    user_id: '',
    username: '',
    real_name: '',
    status: 1,
    password: '',
    new_password: ''
  })
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await userFormRef.value.validate()

    if (isAdd.value) {
      // 新增用户
      const { user_id, new_password, ...addData } = userForm
      await addUser(addData)
      ElMessage.success('添加成功')
    } else {
      // 编辑用户
      const updateData = {
        user_id: userForm.user_id,
        real_name: userForm.real_name,
        status: userForm.status
      }
      // 如果有新密码则添加
      if (userForm.new_password) {
        updateData.password = userForm.new_password
      }
      await updateUser(updateData)
      ElMessage.success('更新成功')
    }

    dialogVisible.value = false
    fetchUserList()
  } catch (error) {
    console.error('操作失败', error)
  }
}
</script>

<style scoped>
.user-management-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-container {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
}

.el-form-item {
  margin-right: 20px;
}

.el-table {
  margin-top: 20px;
}
</style>